from flask import Blueprint, request, jsonify, current_app
import time
from flask_jwt_extended import jwt_required
from app.utils.mongo import db
from bson import ObjectId

# 创建蓝图
ar_culture_bp = Blueprint('ar_culture', __name__, url_prefix='/api')

@ar_culture_bp.post('/ar/getMarker')
@jwt_required()
def get_ar_marker():
    """根据建筑类型获取AR标记信息（返回3D模型和音频）"""
    start_time = time.time()
    data = request.json
    building_type = data.get('building_type')  # 前端传入的建筑类型
    
    if not building_type:
        return jsonify({"code": -1, "msg": "缺少建筑类型参数"}), 400
    
    # 允许的客家建筑类型，与数据库中ar_markers集合的building_type对应
    ALLOWED_BUILDING_TYPES = ['round_tulou', 'square_tulou', 'weilong_house', 'four_corner_house']
    
    try:
        # 检查是否为允许的建筑类型
        if building_type not in ALLOWED_BUILDING_TYPES:
            return jsonify({
                "code": 1,  # 1表示识别到但未开放
                "msg": "该建筑类型暂未开放AR解说",
                "data": None
            })
        
        # 从数据库查询对应的AR标记信息
        marker = db.ar_markers.find_one({"building_type": building_type})
        if not marker:
            # 如果没有找到模型，返回友好提示而非错误
            return jsonify({
                "code": 1,
                "msg": f"{building_type}的AR模型正在开发中，敬请期待",
                "data": None
            })
        
        # 处理返回数据（包含3D模型和音频相关信息）
        result = {
            "id": str(marker["_id"]),
            "building_type": marker["building_type"],
            "name": marker["name"],
            "description": marker["description"],
            "model_url": marker["model_url"],  # 3D模型URL
            "audio_urls": marker["audio_urls"],  # 音频URL集合
            "created_at": marker["created_at"].isoformat() if "created_at" in marker else None,
            "updated_at": marker["updated_at"].isoformat() if "updated_at" in marker else None
        }
        
        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": result
        })
        
    except Exception as e:
        current_app.logger.error(f"获取AR标记失败: {str(e)}")
        return jsonify({"code": -1, "msg": f"获取失败：{str(e)}"}), 500